package utils

import (
	"encoding/base64"
	"gopkg.in/yaml.v3"
	"io/ioutil"
	"log"
	"math/rand"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type Config struct {
	TaskQueue       TaskConfig      `yaml:"task_queue"`
	Redis           RedisConfig     `yaml:"redis"`
	SDWebUI         SDWebUIConfig   `yaml:"sd_webui"`
	DownloadPath    DownloadPath    `yaml:"download_path"`
	AliyunTranslate AliyunTranslate `yaml:"aliyun"`
	Port            string          `yaml:"port"`
}

//task_queue:
//redis: "127.0.0.1:6379"
//pwd: ""
//dbnum: 9
//poolsize: 10

type TaskConfig struct {
	Redis    string `yaml:"redis"`
	Port     string `yaml:"port"`
	Pwd      string `yaml:"pwd"`
	Dbnum    int    `yaml:"dbnum"`
	PoolSize int    `yaml:"poolsize"`
}

type RedisConfig struct {
	Category string `yaml:"category"`
	HOST     string `yaml:"host"`
	Port     string `yaml:"port"`
	Password string `yaml:"password"`
	Database int    `yaml:"database"`
}

type SDWebUIConfig struct {
	IP   string `yaml:"ip"`
	Port string `yaml:"port"`
	Url  string `yaml:"url"`
}

type DownloadPath struct {
	Path string `json:"path"`
	Url  string `json:"url"`
}

type AliyunTranslate struct {
	AccessKeyId     string `yaml:"access_key_id"`
	AccessKeySecret string `yaml:"access_key_secret"`
}

var Cfg *Config // 声明全局变量

func InitConfig() {
	var err error
	Cfg, err = LoadConfig() // 初始化全局变量
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}
}

func LoadConfig() (*Config, error) {
	f, err := os.Open("config/config.yml")
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var cfg Config
	decoder := yaml.NewDecoder(f)
	err = decoder.Decode(&cfg)
	if err != nil {
		return nil, err
	}

	cfg.SDWebUI.Url = "http://" + cfg.SDWebUI.IP + ":" + cfg.SDWebUI.Port
	return &cfg, nil
}

// 生成任务ID

func GenerateTaskID() string {
	rand.Seed(time.Now().UnixNano())
	str := "SD_TASK_ID_"
	return str + strconv.FormatInt(time.Now().UnixNano(), 10) + strconv.Itoa(rand.Intn(10000))
}

// 保存base64编码的图片

func SaveEncodedImage(b64Image string, outputPath string) error {
	decodedImage, err := base64.StdEncoding.DecodeString(b64Image)
	if err != nil {
		return err
	}

	err = ioutil.WriteFile(outputPath, decodedImage, 0644)
	if err != nil {
		return err
	}

	return nil
}

// 以taskid为文件夹名称创建文件夹
func CreateTaskDir(taskId string) (string, error) {
	dir := filepath.Join(Cfg.DownloadPath.Path, taskId)
	err := os.MkdirAll(dir, 0777)
	if err != nil {
		return "", err
	}
	return dir, nil
}

type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func SuccessResponse(data interface{}) Response {
	return Response{
		Code: 200,
		Msg:  "success",
		Data: data,
	}
}

func ErrorResponse(code int, msg string) Response {
	return Response{
		Code: code,
		Msg:  msg,
		Data: nil,
	}
}

func ConvertToURL(path string) string {
	// 将文件路径中的目录部分替换为服务器地址和静态文件服务的路径
	url := strings.Replace(path, Cfg.DownloadPath.Path, Cfg.DownloadPath.Url, 1)
	// 将路径中的反斜杠替换为斜杠
	url = strings.Replace(url, "\\", "/", -1)
	return url
}
